<html><head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="all,follow">
    <!-- 新 Bootstrap 核心 CSS 文件 -->
    <link href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <link rel="stylesheet" href="webuploader/webuploader.css">
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="webuploader/webuploader.js"></script>
<body>
<div class="d-flex align-items-stretch">
    <div class="page-holder w-100 d-flex flex-wrap">
        <div class="container-fluid px-xl-5">
            <section class="py-5">
                <div class="row">
                    <!-- Basic Form-->
                    <div class="col-lg-6 mb-5">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="h6 text-uppercase mb-0">文件上传下载(示例)</h3>
                            </div>
                            <div class="card-body">
                                <form id="sampleUpload" action="/upload" enctype="multipart/form-data" method="post">
                                    <input type="file" name="file">
                                    <button type="submit" class="btn btn-primary">上传</button>

                                </form>
                                <div id="file_msg"></div>
                            </div>
                        </div>
                    </div>
                    <!-- Horizontal Form-->
                    <div class="col-lg-6 mb-5">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="h6 text-uppercase mb-0">图片上传(含缩略图)</h3>
                            </div>
                            <div class="card-body">
                                <form id="imageUpload" action="/image/upload"  enctype="multipart/form-data" method="post" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg">
                                    <input type="file" name="file">
                                    <button type="submit" class="btn btn-primary">上传</button>
                                </form>
                                <div id="image_display"></div>
                            </div>
                        </div>
                    </div>
<!--                    &lt;!&ndash; Inline Form&ndash;&gt;-->
                    <div class="col-lg-6 mb-5">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="h6 text-uppercase mb-0">图片上传并生成缩略图</h3>
                            </div>
                            <div class="card-body">
                                <form class="form-inline">
                                    <div id="uploader" class="wu-example">
                                        <div class="btns">
                                            <div id="picker">选择文件</div>
                                            <div id="ctlBtn" class="webuploader-upload">开始上传</div>
                                        </div>
                                        <!--用来存放文件信息-->
                                        <div id="thelist" class="uploader-list"></div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                    <!-- Modal Form-->
                    <div class="col-lg-6 mb-5">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="h6 text-uppercase mb-0">断点续传</h3>
                            </div>
                            <div class="card-body">
                                <button type="button" data-toggle="modal" data-target="#myModal" class="btn btn-primary">Form in a simple modal </button>
                                <!-- Modal-->
                                <div id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true" class="modal fade text-left">
                                    <div role="document" class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h4 id="exampleModalLabel" class="modal-title">Signin Modal</h4>
                                                <button type="button" data-dismiss="modal" aria-label="Close" class="close"><span aria-hidden="true">×</span></button>
                                            </div>
                                            <div class="modal-body">
                                                <p>Lorem ipsum dolor sit amet consectetur.</p>
                                                <form>
                                                    <div class="form-group">
                                                        <label>Email</label>
                                                        <input type="email" placeholder="Email Address" class="form-control">
                                                    </div>
                                                    <div class="form-group">
                                                        <label>Password</label>
                                                        <input type="password" placeholder="Password" class="form-control">
                                                    </div>
                                                    <div class="form-group">
                                                        <input type="submit" value="Signin" class="btn btn-primary">
                                                    </div>
                                                </form>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" data-dismiss="modal" class="btn btn-secondary">Close</button>
                                                <button type="button" class="btn btn-primary">Save changes</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
</div>
<script src="https://cdn.bootcss.com/jquery.form/4.2.2/jquery.form.js"></script>
<script src="geoUploader.js"></script>

<script>
    $(function () {
        $('#sampleUpload').ajaxForm(function (data) {
            $("#file_msg").append("<div class=\"alert alert-success\" role=\"alert\">上传成功,文件地址:"+data.content+"</div>");
            $("#file_msg").append("<a href='/file/"+data.content+"'>点击下载</a>");
            console.log(data);
            // if (data.status === "fail") {
            //     alert(data.reason)
            // } else {
            //     alert("xxx！");
            //     window.location.reload()
            // }
        });

        $('#imageUpload').ajaxForm(function (data) {
            $("#image_display").append("<img src='/file/"+data.content+"' />");
            const imagePath = data.content;
            const imageName = imagePath.substr(0,imagePath.lastIndexOf("."));
            console.log(imageName);
            const imageSuffix = imagePath.substr(imagePath.lastIndexOf("."),imagePath.length);
            console.log(imageSuffix);
            $("#image_display").append("<img src='/file/"+imageName+"_150x150"+imageSuffix+"' />");
        });


        var test = $("#ctlBtn").tabs({
            url:'127.0.0.1'
        });

        test.init();
        //开始上传按钮
        var $btn = $('#ctlBtn');
        //文件信息显示区域
        var $list = $('#thelist');
        //当前状态
        var state = 'pending';
        //待上传文件的md5值（key为file id）
        var md5 = {};
        var chunkUploadInfo = {};
        /**分片阈值*/
        var chunkedHoldSize = 50 * 1024 * 1024;
        /**分片大小*/
        var chunkedSize = 10 * 1024 * 1024;
        /**上传线程数**/
        var chunkedThreadNum = 3;

        // WebUploader提供的钩子（hook），在文件上传前先判断服务是否已存在这个文件
        WebUploader.Uploader.register({
            'before-send-file': 'beforeSendFile', //整个文件上传前
            'before-send':'beforeSend'//分片上传前
        }, {
            beforeSendFile: function( file ) {
                var that = this;
                var deferred = WebUploader.Deferred();
                uploader.options.formData.md5 = md5[file.id];
                uploader.options.formData.chunkSize = chunkedSize;
                uploader.options.formData.fileSize = file.source.size;
                uploader.options.formData.ext = file.source.ext;
                /**上传前是否需要分片**/
                if(file.size > chunkedHoldSize){
                    /**是否使用分片*/
                    uploader.options.chunked = true;
                    /**分片大小*/
                    uploader.options.chunkSize = chunkedSize;
                    /**分片重试*/
                    uploader.options.chunkRetry = false;
                    /**上传线程数*/
                    uploader.options.threads = chunkedThreadNum;
                    /**上传连接**/
                    uploader.options.server = 'file/uploadChunk';
                }else{
                    uploader.options.chunked = false;
                    uploader.options.server = 'file/uploadOffice';
                }

                /**判断秒传(md5校验),是否续传**/
                //上传前请求服务端,判断文件是否已经上传过
                $.post("file/getUploadPreInfo",
                    {
                        md5:md5[file.id],
                        type:file.source.type,
                        lastModifiedDate: file.source.lastModifiedDate,
                        fileSize: file.source.size,
                        name: file.source.name,
                        chunkSize: chunkedSize
                    },
                    function(data)
                    {
                        console.log(data);
                        if(data.status == '100'){ /**秒传**/
                            that.owner.skipFile(file);
                            deferred.resolve();
                        }else if(data.status == '101'){/**续传**/
                            chunkUploadInfo = data.chunkInfo;
                            deferred.resolve();
                        }else{
                            deferred.resolve();
                        }
                });
                return deferred.promise();
            },
            beforeSend: function(block){
                console.log(chunkUploadInfo);
                var deferred = WebUploader.Deferred();
                if(chunkUploadInfo!= null && contains(chunkUploadInfo,block.chunk+'')){
                    console.log("包含这个块:"+block.chunk.toString());
                    deferred.reject();
                }else{
                    deferred.resolve();
                }
                return deferred.promise();
            }
        });

        //初始化Web Uploaderl
        var uploader = WebUploader.create({
            // swf文件路径
            swf: 'webuploader/Uploader.swf',
            // 文件接收服务端。
            server: 'file/uploadChunk',
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: '#picker',
            formData: {
                md5: ''
            }
        });

        // 当有文件被添加进队列的时候（选择文件后调用）
        uploader.on( 'fileQueued', function( file ) {
            $list.append( '<div id="' + file.id + '" class="item">' +
                '<h4 class="info">' + file.name + '</h4>' +
                '<p class="md5"></p>' +
                '<p class="state"></p>' +
                '</div>' );
            //获取文件MD5值
            md5[file.id] = '';
            uploader.md5File( file )// 及时显示进度
                .progress(function(percentage) {
                    $( '#'+file.id ).find('.md5').text('读取文件：'+parseInt(percentage*100)+"%");
                })
                // 完成
                .then(function(val) {
                    md5[file.id] = val;
                    $( '#'+file.id ).find('.md5').text('md5值：' + val);
                    $( '#'+file.id ).find('.state').text('等待上传...');
                });
        });


        /**附件上传**/
        uploader.on( 'uploadStart' , function(file){
            console.log(file);
            // if(file.size > 1000){
            //     uploader.chunked = true;
            //     uploader.chunkSize = 1024;
            //     uploader.chunkRetry =  false;
            //     uploader.threads = 3;
            // }
        });


        // 文件上传过程中创建进度条实时显示。
        uploader.on( 'uploadProgress', function( file, percentage ) {
            var $li = $( '#'+file.id );
            $li.find('p.state').text('上传中（' + parseInt(percentage * 100) + '%）');
        });

        // 文件上传成功后会调用
        uploader.on( 'uploadSuccess', function( file ) {
            /**附件上传成功后，调用合并的接口*/
            $.post("file/mergeChunk", {
                    md5 : md5[file.id],
                    fileSize: file.source.size,
                    name: file.source.name,
                    chunkSize: chunkedSize
                },function(result){
                    console.log(result);
                $( '#'+file.id ).find('p.state').text('上传出错');
            });
            $( '#'+file.id ).find('p.state').text('已上传');
        });

        // 文件上传失败后会调用
        uploader.on( 'uploadError', function( file ) {
            $( '#'+file.id ).find('p.state').text('上传出错');
        });

        // 文件上传完毕后会调用（不管成功还是失败）
        uploader.on( 'uploadComplete', function( file ) {
            $( '#'+file.id ).find('.progress').fadeOut();
        });

        // all事件（所有的事件触发都会响应到）
        uploader.on( 'all', function( type ) {
            if ( type === 'startUpload' ) {
                state = 'uploading';
            } else if ( type === 'stopUpload' ) {
                state = 'paused';
            } else if ( type === 'uploadFinished' ) {
                state = 'done';
            }

            if ( state === 'uploading' ) {
                $btn.text('暂停上传');
            } else {
                $btn.text('开始上传');
            }
        });

        // 开始上传按钮点击事件响应
        $btn.on( 'click', function() {
            if ( state === 'uploading' ) {
                uploader.stop();
            } else {
                // 不存在则上传文件
                uploader.upload();
            }
        });
    })



    function contains(arr, obj) {
        var i = arr.length;
        while (i--) {
            if (arr[i] === obj) {
                return true;
            }
        }
        return false;
    }

</script>
</body>
</html>